require "import"
import "android.media.*"
import "java.io.File"
import "android.os.*"
import "android.content.*"
import "android.net.*"
import "android.widget.*"
import "android.view.View"
import "com.androlua.*"

local vibrator = this.getSystemService(this.VIBRATOR_SERVICE)
if vibrator then vibrator.vibrate(100) end

local folderPath = Environment.getExternalStorageDirectory().getAbsolutePath().."/ghi âm bằng tiện ích/"
local file = File(folderPath)
if not file.exists() then success = file.mkdirs() end

function playMusic(player)
    if mp then
        mp.stop()
        mp = nil
    else
        mp = MediaPlayer()
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC)
        mp.reset()
        mp.setDataSource(player)
        mp.prepare()
        mp.start()
        mp.setOnCompletionListener {
            onCompletion = function()
                mp.release()
                mp = nil
            end        }
    end
    return true
end

local bitRateNames, bitRateValues = {"32 kbps", "64 kbps", "96 kbps", "128 kbps", "160 kbps", "192 kbps", "256 kbps", "320 kbps", "480 kbps"}, {32000, 64000, 96000, 128000, 160000, 192000, 256000, 320000,48000}
if not service.getSharedData("defaultAudioBitrate") then
    service.setSharedData("defaultAudioBitrate", bitRateValues[1])
end

local dlg = LuaDialog()
dlg.setCancelable(false)
dlg.setTitle("Chọn tốc độ Bit")
dlg.setSingleChoiceItems(bitRateNames, table.find(bitRateValues, service.getSharedData("defaultAudioBitrate")) - 1)
dlg.setButton2("Lưu")
dlg.onItemClick = function(l, v, p, i)
    service.setSharedData("defaultAudioBitrate", bitRateValues[i])
    return
end

local focus = service.getText(node)
if focus == "Tùy chọn khác" or focus == "Hiển thị thêm" then
    dlg.show()
    return
end

if mr then
    mr.pause()
    focus2 = this.getText(node)
    appName = this.getAppName(node)
    local dlg = LuaDialog()
    dlg.setTitle("Đang tạm từng ghi âm")
    dlg.setButton("Tiếp tục ghi", function()
        mr.resume()
    end)
    dlg.setButton2("Dừng ghi", function()
        mr.stop()
        mr.release()
        mr = nil
        if vibrator then vibrator.vibrate(100) end
        local layout = {
            LinearLayout,
            orientation = "vertical",
            {
                Button,
                text = "Phát",
                onClick = function()
                    playMusic(outputFile)
                end
            },
            {
                Button,
                text = "Chia sẻ",
                onClick = function()
                    this.click({{"<"..focus2.."@"..appName..">9000000$10", function()
                        dlg2.show()
                    end}})
                    service.shareFile(outputFile)
                    dlg2.hide()
                end
            },
            {
                Button,
                text = "Xoá",
                onClick = function()
                    os.remove(outputFile)
                    service.postSpeak(1200, "Đã xoá bản ghi")
                    dlg2.dismiss()
                end
            },
            {
                Button,
                text = "mở trong trình quản lý tập tin",
                onClick = function()
                    this.startActivity(Intent(Intent.ACTION_VIEW).setDataAndType(Uri.parse(folderPath), "resource/folder"))
                    dlg2.dismiss()
                end            },
            {
                Button,
                text = "Hướng dẫn",
                onClick = function()
            print("Chạy tiện ích mở rộng này khi tập trung vào Tùy chọn khác, Thêm tùy chọn hoặc tương tự để chọn chất lượng ghi âm.")
            print("Để ghi, hãy chạy tiện ích mở rộng này trên bất kỳ tiêu điểm nào khác ngoài tiêu điểm ở trên.")
            print("Để tạm dừng ghi, hãy chạy lại tiện ích mở rộng này và nó sẽ hiển thị các tùy chọn để tiếp tục hoặc dừng bản ghi đang tạm dừng.")
            print("Lưu ý: Đảm bảo tiêu điểm cuối cùng trước khi dừng ghi là màn hình chính.")
            print("Vì vậy, hộp thoại lựa chọn có thể xuất hiện lại sau khi chia sẻ tệp ghi âm và quay lại màn hình trước đó.")
                end
            }
        }
        dlg2 = LuaDialog(this)
        dlg2.View = loadlayout(layout)
        dlg2.setCancelable(false)
        dlg2.setTitle("Kết quả "..fileName)
        dlg2.setButton2("Đóng")
        dlg2.onDismiss = function()
            appName = nil
            focus2 = nil
            fileName = nil
            layout = nil
            dlg2 = nil
            this.playSoundGestureEnd()
        end
        dlg2.show()
    end)
    dlg.setButton3("Ẩn hộp thoại")
    dlg.show()
    this.postClick(500, {{"<Dừng ghi"}})
else
    if fileName == nil then
        fileName = os.date("Bản ghi âm_%Y_%m_%d_%H_%M_%S.mp3")
        this.playSoundGestureBegin()
    end
    outputFile = folderPath..fileName
    mr = MediaRecorder()
    mr.setAudioSource(MediaRecorder.AudioSource.MIC)
    mr.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
    mr.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
    mr.setAudioEncodingBitRate(service.getSharedData("defaultAudioBitrate"))
    mr.setOutputFile(outputFile)
    mr.prepare()
    mr.start()
end